package com.mgq.java8.collector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import static com.mgq.java8.collector.CollectorHarness.partitionPrimes;
import static java.util.stream.Collectors.partitioningBy;

/**
 * <b>功能：</b>测试性能类<br>
 * <b>Copyright mgq</b>
 * <li>版本&nbsp;&nbsp;&nbsp;&nbsp;修改日期&nbsp;&nbsp;&nbsp;&nbsp;部　　门&nbsp;&nbsp;&nbsp;&nbsp;作　者&nbsp;&nbsp;&nbsp;&nbsp;变更内容</li><hr>
 * <li>v1.0&nbsp;&nbsp;&nbsp;&nbsp;20220404&nbsp;&nbsp;营业后台&nbsp;&nbsp;&nbsp;&nbsp;马广奇&nbsp;&nbsp;&nbsp;&nbsp;创建类</li>
 * <br><br>
 *
 * @author 马广奇
 * @version 2022-04-04 12:27
 */
public class CollectorHarness {
    public static void main(String[] args) {
        //取最快的时间
        long fastest = Long.MAX_VALUE;
        //运行10次,取最快的时间
        for (int i = 0; i < 10; i++) {
            long start = System.nanoTime();
            //计算前100万的质数和非质数
             partitionPrimes(3_000_000);
            //partitionPrimesWithCustomCollector(3_000_000);
            //取毫秒值
            long duration = (System.nanoTime() - start) / 1_000_000;
            if (duration < fastest) fastest = duration;
        }
        System.out.println("最快的用时:" + fastest + "毫秒");
    }

    /**
     * <b>功能描述：</b>使用传统的方法求质数<br>
     * <b>修订记录：</b><br>
     * <li>20220404&nbsp;&nbsp;|&nbsp;&nbsp;马广奇&nbsp;&nbsp;|&nbsp;&nbsp;创建方法</li><br><br>
     *
     * @param n 计算1-n的质数
     * @return Map<Boolean, List < Integer>>
     */

    public static Map<Boolean, List<Integer>> partitionPrimes(int n) {
        return IntStream.rangeClosed(2, n).boxed().collect(partitioningBy(CollectorHarness::isPrime));
    }

    /**
     * <b>功能描述：</b>使用自定义的收集器求质数<br>
     * <b>修订记录：</b><br>
     * <li>20220404&nbsp;&nbsp;|&nbsp;&nbsp;马广奇&nbsp;&nbsp;|&nbsp;&nbsp;创建方法</li><br><br>
     *
     * @param n 计算1-n的质数
     * @return Map<Boolean, List < Integer>>
     */

    public static Map<Boolean, List<Integer>> partitionPrimesWithCustomCollector(int n) {
       return IntStream.rangeClosed(2, n).boxed()
                .collect(new PrimeNumbersCollector());
    }


    /**
     * <b>功能描述：</b>判断是否是质数<br>
     * <b>修订记录：</b><br>
     * <li>20220404&nbsp;&nbsp;|&nbsp;&nbsp;马广奇&nbsp;&nbsp;|&nbsp;&nbsp;创建方法</li><br><br>
     *
     * @param candidate 候选数
     * @return boolean
     */

    public static boolean isPrime(int candidate) {
        int candidateRoot = (int) Math.sqrt(candidate);
        return IntStream.rangeClosed(2, candidateRoot).noneMatch(i -> candidate % i == 0);
    }
}
